package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author He Kuntao
 * @desc TODO
 * @date 2024/2/26 19:31
 */
public class SimpleRedisLock implements ILock {

    /**
     * 锁的key
     */
    private final String lockKey;
    /**
     * redisTemplate
     */
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 锁前缀
     */
    public static final String KEY_PREFIX = "lock:";
    /**
     * ID前缀
     */
    public static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    /**
     * 解锁脚本
     */
    public static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("lua/unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String lockKey, StringRedisTemplate stringRedisTemplate) {
        this.lockKey = lockKey;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁
     *
     * @param timeoutSec 锁持有超时时间，过期自动释放锁
     * @return true 获取成功，false 获取失败
     */
    @Override
    public boolean tryLock(Long timeoutSec) {
        // 获取当前线程标识，用于存入value
        String threadId = ID_PREFIX + Thread.currentThread().getId();

        // 获取锁
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + lockKey,
                threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    /**
     * 释放锁-lua
     */
    @Override
    public void unlock() {
        // 调用lua脚本，可以使用static初始化块，提前加载脚本
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + lockKey),
                ID_PREFIX + Thread.currentThread().getId());
    }


    /*   @Override
    public void unlock() {
        *//* 防止误删锁 *//*
        // 获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁中的标识
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + lockKey);
        if (threadId.equals(id)) {
            stringRedisTemplate.delete(KEY_PREFIX + lockKey);
        }
    }*/
}
